package com.skyworthclub.competition.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.skyworthclub.competition.beans.User;
import com.skyworthclub.competition.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author li
 * @version 1.0
 * @since 18-10-15 下午7:27
 * 认证成功后的逻辑
 **/
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        //获取用户信息
        User user = userService.getUserInfo(authentication.getName());
        user.setPassword(null);
        //设置token和状态码
        httpServletResponse.addHeader("token", "token");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        Map<String, Object> map = new HashMap<>(4);
        map.put("status", 200);
        map.put("message", "登录成功");
        map.put("userInfo", user);
        //返回json提示信息
        httpServletResponse.getWriter().write(JSON.toJSONString(map));
        httpServletResponse.getWriter().flush();
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
